<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      v-show="showSearch"
      :inline="true"
      @submit.native.prevent
    >
      <el-form-item label="组织名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入"
          clearable
          size="small"
          style="width: 240px"
          @change="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button-group>
          <el-button
            size="small"
            @click="changeQuery(2)"
            :type="queryParams.category == 2 ? 'primary' : 'default'"
            >仅班组</el-button
          >
          <el-button
            size="small"
            @click="changeQuery(3)"
            :type="queryParams.category == 3 ? 'primary' : 'default'"
            >仅区域</el-button
          >
          <el-button
            size="small"
            @click="changeQuery(4)"
            :type="queryParams.category == 4 ? 'primary' : 'default'"
            >仅组别</el-button
          >
          <el-button
            size="small"
            @click="changeQuery(5)"
            :type="queryParams.category == 5 ? 'primary' : 'default'"
            >仅岗位</el-button
          >
        </el-button-group>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          plain
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain size="mini" @click="handleDelete"
          >删除
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="default" plain size="mini" @click="handleAdd"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="default" plain size="mini" @click="handleAdd"
          >导入
        </el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getTableRecords"
      ></right-toolbar>
    </el-row>
    <!-- 选中提示 -->
    <div class="choice-tips" v-if="multipleSelection.length > 0">
      <div style="display: flex; align-item: center">
        <i
          class="el-icon-warning"
          style="color: #078fea; font-size: 20px; margin-right: 5px"
        ></i>
        <span style="font-size: 14px"
          >已选择<span style="color: #078fea"
            >&nbsp;{{ multipleSelection.length }}&nbsp;</span
          >项</span
        >
      </div>
    </div>
    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="records"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="id" prop="id" v-if="false" />
      <el-table-column label="序号" type="index" width="100"></el-table-column>
      <el-table-column label="组织名称" prop="deptName" min-width="150" />
      <el-table-column label="组织类型" prop="category" min-width="150">
        <template slot-scope="scope">
          {{ scope.row.category | cateFilter }}
        </template>
      </el-table-column>
      <el-table-column label="上级组织" prop="parentName" min-width="150">
        <template slot-scope="scope">
          {{ scope.row.parentName == "" ? "/" : scope.row.parentName }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" min-width="150" />
      <el-table-column label="排序" prop="orderNum" width="100" />
      <el-table-column label="停用/启用" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="'0'"
            :inactive-value="'1'"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        min-width="200"
        class-name="small-padding fixed-width"
      >
        <template scope="scope">
          <el-button
            v-show="scope.row.status == '1'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-details"
            @click="details(scope.row)"
            >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getTableRecords"
    />
<!--    <pagination-->
<!--      v-show="total > 10"-->
<!--      :total="total"-->
<!--      :page.sync="queryParams.pageNum"-->
<!--      :limit.sync="queryParams.pageSize"-->
<!--      :page-sizes="[10]"-->
<!--      @pagination="getTableRecords"-->
<!--    />-->
    <!-- 提交表单 -->
    <el-dialog
      :title="form.title"
      :visible.sync="formOpen"
      width="780px"
      :showClose="false"
      append-to-body
    >
      <el-form
        :model="form"
        ref="form"
        label-width="80px"
        inline
        :disabled="!formEnable"
      >
        <el-form-item label="组织名称" prop="deptName" :rules="rules.deptName">
          <el-input
            v-model="form.deptName"
            class="form-inp"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="所属类型" prop="category">
          <el-select
            v-model="form.category"
            class="form-inp"
            clearable
            @change="categoryChange"
            :disabled="form.deptId != undefined"
          >
            <el-option
              v-for="(v, k) in cateOptions"
              :key="k"
              :label="v.label"
              :value="v.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="上级菜单"
          prop="parentId"
          :rules="form.category > 2 ? rules.parentId : []"
        >
          <el-cascader
            :disabled="!form.category || form.category < 3"
            v-model="tmpList"
            class="form-inp"
            ref="cascaderHandler"
            :options="casOptions"
            :props="{ checkStrictly: true, value: 'id', label: 'label' }"
            @change="casChange"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number
            class="form-inp"
            v-model="form.orderNum"
            controls-position="right"
            @change="numChange"
            :min="1"
          ></el-input-number>
        </el-form-item>

        <div v-if="form.category === 5">
          <el-form-item label="岗位补贴" prop="jobAllowance" >
            <el-input v-model="form.jobAllowance" placeholder="请输入价格" :disabled="form.allowanceStatus !== 0">
              <i slot="suffix" style="margin-right: 10px;">元</i>
            </el-input>
          </el-form-item>
          <el-form-item label="补贴状态" prop="allowanceStatus">
            <el-radio-group v-model="form.allowanceStatus">
              <el-radio :label="0">启用</el-radio>
              <el-radio :label="2">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <el-form-item label="岗位状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit" v-if="formEnable">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addDept,
  deptOptions,
  tableRecords,
  deleteMultipart,
  changeStataus,
  updateDept,
} from "@/api/system/dept.js";
export default {
  data() {
    return {
      loading: false,
      // 表单是否可用
      formEnable: true,
      // 每页数量
      total: 0,
      showSearch: true,
      // 提交表单
      formOpen: false,
      // 表格数据选中列表
      multipleSelection: [],
      // 表格记录
      records: [],
      // 级联选项
      casOptions: [],
      // 级联回显tmp
      tmpList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptName: null,
        category: null,
      },
      // 类别可选项
      cateOptions: [
        { label: "班组", value: 2 },
        { label: "区域", value: 3 },
        { label: "组别", value: 4 },
        { label: "岗位", value: 5 },
      ],
      // 表单
      form: {
        title: "新增组织",
        status: "0",
        orderNum: 1,
        ancestores: "0",
        parentId: undefined,
        category: undefined,
        allowanceStatus: 2,
      },
      rules: {
        parentId: [
          { required: true, trigger: "blur", message: "需要指定上级组织" },
        ],
        deptName: [
          { required: true, trigger: "blur", message: "名称不能为空" },
        ],
      },
    };
  },
  filters: {
    cateFilter(v) {
      switch (v) {
        case 2:
          return "班组";
        case 3:
          return "区域";
        case 4:
          return "组别";
        case 5:
          return "岗位";
        default:
          return "未知";
      }
    },
  },
  created() {
    this.getTableRecords();
  },
  methods: {
    // 初始化页面
    init() {
    },
    // '仅'条件查询
    changeQuery(v) {
      this.queryParams.pageNum = 1;
      if (this.queryParams.category == v) {
        this.queryParams.category = null;
      } else {
        this.queryParams.category = v;
      }
      this.getTableRecords();
    },
    async categoryChange() {
      // this.$refs.form.clearValidate();
      if (this.form.category) {
        const res = await deptOptions(this.form.category);
        this.casOptions = res.data;
      }
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getTableRecords();
    },
    // 表单重置
    reset() {
      this.form = {
        title: "新增班组",
        status: "0",
        orderNum: 1,
        ancestores: "0",
        parentId: undefined,
        category: undefined,
      };
      this.tmpList = [];
    },
    // 新增按钮
    handleAdd() {
      this.formEnable = true;
      this.reset();
      this.formOpen = true;
    },
    // 删除按钮
    handleDelete() {
      const waitDeleteIds = [];
      let flag = false;

      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先选择数据");
        return;
      }
      for (var i = 0; i < this.multipleSelection.length; i++) {
        if (this.multipleSelection[i].status == "0") {
          this.$message.error("选中数据中有仍在启用状态的数据，无法删除");
          flag = true;
          return;
        }
        waitDeleteIds.push(this.multipleSelection[i].deptId);
      }
      this.$confirm(
        `删除班组、区域或组别，将同时删除它的下级组织，确认删除吗?`,
        "删除确认",
        {}
      ).then(() => {
        deleteMultipart({ ids: waitDeleteIds })
          .then((res) => {
            this.$message.success(res.msg);
            this.getTableRecords();
          })
          .catch((err) => {
            this.$message.error("删除失败：", err);
          });
      });
    },
    // 上级菜单选中
    casChange(v) {
      this.$refs.cascaderHandler.dropDownVisible = false;
      this.form.ancestores += v.join(",");
      this.form.parentId = v[v.length - 1];
    },
    // 获取表格数据
    getTableRecords() {
      this.loading = true;
      tableRecords(this.queryParams)
        .then((res) => {
          this.records = res.rows;
          this.total = res.total;
          this.loading = false;
        })
        .catch((err) => {
        });
    },
    // 详情
    async details(row) {
      this.formEnable = false;
      this.loading = true;
      this.form = row;
      this.form["title"] = "组织详情";
      await this.categoryChange();
      this.tmpList = row.ancestors
        .split(",")
        .slice(1)
        .map((i) => {
          return parseInt(i);
        });
      this.loading = false;
      this.formOpen = true;
    },
    // 修改
    async handleUpdate(row) {
      this.formEnable = true;
      this.loading = true;
      this.form = row;
      this.form["title"] = "组织修改";
      await this.categoryChange();
      this.tmpList = row.ancestors
        .split(",")
        .slice(1)
        .map((i) => {
          return parseInt(i);
        });
      this.loading = false;
      this.formOpen = true;
    },
    // 停用启用
    handleStatusChange(row) {
      const temp = row.status; // 修改之后的状态
      const oldStatus = temp == "1" ? "0" : "1";
      row.status = oldStatus;
      let confirmText = "";

      confirmText = row.status == "1" ? "停用" : "启用";
      this.$confirm(
        `修改状态将同时影响它的子结构，确认${confirmText}该组织结构吗？`,
        "状态修改",
        {}
      ).then(() => {
        this.loading = true;
        row.status = temp;
        changeStataus(row)
          .then((res) => {
            this.$message.success(res.msg);
            this.getTableRecords();
            this.loading = false;
          })
          .catch(() => {
            row.status = oldStatus;
            this.loading = false;
          });
      });
    },
    // 表格多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        deptName: null,
        category: null,
      };
      this.getTableRecords();
    },
    // 表单提交
    submit() {
      if (this.form.deptId) {
        updateDept(this.form).then((res) => {
          this.$message.success(res.msg);
          this.formOpen = false;
          this.getTableRecords();
          this.$refs.cascaderHandler.$refs.panel.clearCheckedNodes(); // 清空级联表
        });
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            addDept(this.form).then((res) => {
              this.$message.success(res.msg);
              this.formOpen = false;
              this.getTableRecords();
              this.$refs.cascaderHandler.$refs.panel.clearCheckedNodes(); // 清空级联表
            });
          }
        });
      }
    },
    // 取消
    cancel() {
      this.formOpen = false;
    },
    // 排序控件
    numChange(v) {
    },
  },
};
</script>

<style scoped>
.choice-tips {
  width: 100%;
  height: 40px;
  background-color: #e6f7ff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 10px;
  border-radius: 5px;
  border: 1px solid #bae7ff;
}

.form-inp {
  width: 250px;
}
</style>
